package com.cbarmstrong.MarketWatcher;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.logging.Logger;

import com.cbarmstrong.Finance.Data;
import com.cbarmstrong.Finance.PairCollection;

public class DoAction {


	static Logger logger=Data.getLogger();
	/**
	 * @param args
	 * @throws InterruptedException 
	 * @throws NumberFormatException 
	 * @throws IOException 
	 */

	public static void main(String[] args) throws NumberFormatException, InterruptedException, IOException {
		logger.info("Recieved "+args.length+" arguments: "+Arrays.toString(args));
		if(args[0].compareTo("GeneratePairs")==0){
			PairCollection pc=new PairCollection(); 
			try {
				pc.createPairs();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(args[0].compareTo("DoBatches")==0){ 
			logger.info("Starting Batch Run");
			CrossOverScheduler cos;
			try {
				cos = new CrossOverScheduler(System.getProperty("ticker","ftse"));
				cos.doGeneratedCross(new Integer(System.getProperty("pairDepth", "2")), new Integer(System.getProperty("batchSize", "1000")));
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(args[0].compareTo("RunGA")==0){
			logger.info("Starting Genetic Run");
			try {
				Connection connection = Data.initConnection();
				Statement s = connection.createStatement(), u = connection.createStatement();
				while(true){
					ResultSet r=s.executeQuery("SELECT id, name FROM stock");
					while(r.next()){
						if(u.executeUpdate("UPDATE locks SET value=1 WHERE key_name='GA "+r.getString("name")+"' and value=0")==0){ continue; }
						String name = r.getString("name");
						int id = r.getInt("id");
						logger.info("Starting run for stock: "+name);
						IndicatorSociety cos = new IndicatorSociety();
						cos.setTicker(name, id);
						cos.initialize();
						cos.run(new Integer(System.getProperty("generations","1000")));
						ResultSet stat=connection.createStatement().executeQuery("SELECT COUNT(*),AVG(deviation),AVG(profit),AVG(fitness),MIN(deviation),MAX(profit) FROM populations WHERE deviation>0 AND stockid="+r.getString("id"));
						if(stat.first()){
							logger.info("Saved "+stat.getString("COUNT(*)")+" chromosomes - Fitness: "+stat.getString("AVG(fitness)")+". Results (Average):");
							logger.info("Deviation: "+stat.getString("MIN(deviation)")+"("+stat.getString("AVG(deviation)")+")");
							logger.info("Profit: "+stat.getString("MAX(profit)")+"("+stat.getString("AVG(profit)")+")");
						}
						else{
							logger.warning("There was some issue with getting the results");
						}
						u.executeUpdate("UPDATE locks SET value=0 WHERE key_name='GA "+name+"' AND value=1");
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(args[0].compareTo("addStock")==0){
			if(args.length!=5){ System.out.println("4 Further arguments required: Name, Y-Ticker and G-Ticker"); System.exit(8); }
			logger.info("Adding stock");
			String name=args[1];
			String ytick=args[2];
			String gtick=args[3];  
			Double spread=new Double(args[4]);
			try {
				Connection con = Data.initConnection();
				Statement s = con.createStatement();
				con.setAutoCommit(false);
				if(s.executeQuery("SELECT * FROM locks WHERE key_name='GA "+name+"'").first()){ logger.severe(name+" already in locks table"); }
				else{ s.executeUpdate("INSERT INTO locks VALUES ( 0 , 'GA "+name+"' )"); }
				if(s.executeQuery("SELECT * FROM locks WHERE key_name='PR "+name+"'").first()){ logger.severe(name+" prices already in locks table"); }
				else{ s.executeUpdate("INSERT INTO locks VALUES ( 0 , 'PR "+name+"' )"); }
				if(s.executeQuery("SELECT * FROM stock WHERE name='"+name+"'").first()){ logger.severe(name+" already in stock table"); }
				else{ s.executeUpdate("INSERT INTO stock VALUES ( default , '"+ytick+"' , '"+gtick+"' , '"+name+"' , "+spread+" , 'yTicker' )"); }
				con.commit();
				con.setAutoCommit(true);
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
		if(args[0].compareTo("delStock")==0){
			if(args.length!=2){ System.out.println("Stock name required"); System.exit(8); }
			logger.info("Removing stock: "+args[1]);
			String name=args[1];
			try {
				Connection con = Data.initConnection();
				Statement s = con.createStatement();
				con.setAutoCommit(false);
				s.executeUpdate("DELETE FROM locks WHERE key_name='GA "+name+"'");
				s.executeUpdate("DELETE FROM stock WHERE name='"+name+"'");
				con.setAutoCommit(true);
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
		if(args[0].compareTo("ClearLock")==0){
			if(args.length!=3){ logger.severe("2 additional parms required - Type (lock/stock), and name"); System.exit(8); }
			String type=args[1], name=args[2];
			logger.info("Clearing "+type+": "+name);
			try{
				Connection con = Data.initConnection();
				Statement s = con.createStatement();
				if(type.compareTo("lock")==0){
					s.executeUpdate("UPDATE locks SET value=0 WHERE key_name='GA "+name+"'");
				}
				if(type.compareTo("host")==0){
					s.executeUpdate("UPDATE hosts SET active=0 WHERE name='"+name+"'");
				}
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
}